package kr.ac.kaist.vrowser.fragments;

import java.util.List;

import kr.ac.kaist.vrowser.R;
import kr.ac.kaist.vrowser.data.FormOptionElement;
import kr.ac.kaist.vrowser.data.FormSelectElement;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FormSelectFragment extends VrowserBaseFragment {
	int myPosition;
	List<FormOptionElement> options;
	FormSelectClick formSelectClick;
	FormSelectElement selectElement;
	
	public static FormSelectFragment newInstance(List<FormOptionElement> options, FormSelectElement selectElement) {
		FormSelectFragment f = new FormSelectFragment();
		f.options = options;
		f.selectElement = selectElement;
		return f;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	public void setFormSelectClick(FormSelectClick formSelectClick) {
		this.formSelectClick = formSelectClick;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_diapad, container, false);
		
		try {
			for (int i = 0; i < options.size(); ++i) {
				final FormOptionElement option = options.get(i);
				
				if (option == null) {
					Button button = (Button)v.findViewById(this.buttons[i]);
					button.setText(app.getResources().getString(R.string.formReturnText));
					button.setContentDescription(app.getResources().getString(R.string.formReturnDesc));
					button.setBackgroundResource(R.drawable.button_formelement);
					button.setTag(option);
					button.setVisibility(View.VISIBLE);
					button.setOnClickListener(new OnClickListener() {
		
						@Override
						public void onClick(View v) {
							if (formSelectClick != null) {
								formSelectClick.onFormSelectClick(option, selectElement);
							}
						}
						
					});
					continue;
				}
				
				Button button = (Button)v.findViewById(this.buttons[i]);
				button.setText(cutWords(option.label, i < 5 && i == (options.size() - 1) && i % 2 == 0));
				button.setContentDescription(String.format(app.getResources().getString(R.string.formButtonDesc), option.label));
				button.setTag(option);
				button.setBackgroundResource(R.drawable.button_formelement);
				button.setVisibility(View.VISIBLE);
				button.setOnClickListener(new OnClickListener() {
	
					@Override
					public void onClick(View v) {
						if (formSelectClick != null) {
							formSelectClick.onFormSelectClick(option, selectElement);
						}
					}
					
				});
			} 
		} catch (Exception e) {
			
		}
		return v;
	}

	public interface FormSelectClick {
		public void onFormSelectClick(FormOptionElement option, FormSelectElement selectElement);
	}
}
